﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace lox_z12Class
{
    class LoxFunction : LoxCallable
    {
        private Stmt.Function declaration;
        private Environment closure;
        private bool isInitializer;
        public LoxFunction(Stmt.Function declaration, Environment closure, bool isInitializer)
        {
            this.isInitializer = isInitializer;
            this.closure = closure;
            this.declaration = declaration;
        }
        public LoxFunction bind(LoxInstance instance)
        {
            Environment environment = new Environment(closure);
            environment.define("this", instance);
            return new LoxFunction(declaration, environment, isInitializer);
        }
        public String ToString() { return "<fn " + declaration.name.lexeme + ">"; }
        public int arity() { return declaration._params.Count(); }
        public Object call(Interpreter interpreter, List<Object> arguments)
        {
            Environment environment = new Environment(closure);
            for (int i = 0; i < declaration._params.Count(); i++)
            {
                environment.define(declaration._params[i].lexeme, arguments[i]);
            }

            try {
                interpreter.executeBlock(declaration.body, environment);
            } catch (Return returnValue) {
                if (isInitializer)
                    return closure.getAt(0, "this");

                return returnValue.value;
            }

            if (isInitializer)
                return closure.getAt(0, "this");

            return null;
        }
    }
}
